package day4;

import flink.RedisSinkFunction;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.connectors.redis.RedisSink;
import org.apache.flink.streaming.connectors.redis.common.config.FlinkJedisPoolConfig;
import org.apache.hadoop.hive.metastore.conf.EnumValidator;

import java.time.Duration;

public class job1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);
        env.enableCheckpointing(5000);

        KafkaSource<String> source = KafkaSource.<String>builder()
                .setBootstrapServers("bigdata1:9092")
                .setTopics("ProduceRecord")
                .setGroupId("day4 job1")
                .setStartingOffsets(OffsetsInitializer.earliest())
                .setValueOnlyDeserializer(new SimpleStringSchema())
                .build();

        FlinkJedisPoolConfig bigdata1 = new FlinkJedisPoolConfig.Builder()
                .setHost("bigdata1")
                .setPort(6379)
                .setPassword("123456")
                .build();

        WatermarkStrategy<String> watermarkStrategy = WatermarkStrategy
                .<String>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                .withTimestampAssigner(new SerializableTimestampAssigner<String>() {
                    @Override
                    public long extractTimestamp(String s, long l) {
                        String[] strings = s.split(",");
                        return Long.parseLong(strings[0]);
                    }
                });

        SingleOutputStreamOperator<String[]> source1 = env.fromSource(source, watermarkStrategy, "source")
                .map(s -> {
                    String[] strings = s.split(",");
                    return new String[]{strings[1], strings[2] , strings[3]};
                }).filter(s -> s[2].equals("1"))
                .keyBy(s -> s[0])
                .window(TumblingProcessingTimeWindows.of(Time.seconds(600)))
                .sum(1);

        source1.addSink(new RedisSink<>(bigdata1 , new day4.RedisSink()));

        env.execute();
    }
}
